#import "AppleMapsPlugin.h"
#import "AppleMapsViewFactory.h"

@interface AppleMapsPlugin()

@property (nonatomic,strong) FlutterEventSink sink;
@property (nonatomic, strong) CLLocationManager *locationManager;

@end


@implementation AppleMapsPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* channel = [FlutterMethodChannel
                                     methodChannelWithName:@"apple_maps"
                                     binaryMessenger:[registrar messenger]];
    AppleMapsPlugin* instance = [[AppleMapsPlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:channel];
    
    FlutterEventChannel * event = [FlutterEventChannel eventChannelWithName:@"apple_maps_eventChannel" binaryMessenger:registrar.messenger];
    [event setStreamHandler:instance];
    
    // 使用Policy，不然触摸原生会失效
    [registrar registerViewFactory:[[AppleMapsViewFactory alloc] initWithMessenger:registrar] withId:@"apple_maps.testView" gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyWaitUntilTouchesEnded];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getPlatformVersion" isEqualToString:call.method]) {
    result([@"iOS" stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  } else if ([@"startCompass" isEqualToString:call.method]) {

      if (!self.locationManager) {
          self.locationManager = [[CLLocationManager alloc] init];
          self.locationManager.delegate = self;
      }
            
      [self.locationManager startUpdatingHeading]; // 开始更新指南针数据
      
      result(NULL);
  } else if ([@"stopCompass" isEqualToString:call.method]) {
      [self.locationManager stopUpdatingHeading];
      result(NULL);
  }
  else  {
    result(FlutterMethodNotImplemented);
  }
}

- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
                                       eventSink:(FlutterEventSink)events{
    self.sink = events;
    return nil;
}
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments{
    return nil;
}

// 告诉flutter
- (void)toFlutter:(CGFloat)heading{
    if (!self.sink) {
        NSLog(@"apple maps插件 出现了sink没有值的情况");
        return;
    }
    
    self.sink(@{@"type":@"heading",@"heading":@(heading)});
}


- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
    // newHeading.magneticHeading 是当前磁北方向的角度
    CGFloat heading = newHeading.magneticHeading;
    [self toFlutter:heading];
}

@end
